# coding=utf-8

import sqlite3 as db
import os
try:
    from Tkinter import *
    from tkMessageBox import *
    MODE = True
except ImportError:
    MODE = False
    


con = None


def get_cars(ui_demo=True):
    try:
        con = db.connect(':memory:')
        cur = con.cursor()    
        cur.execute("CREATE TABLE car(id INT, name TEXT)")
        cars = [u"兰博',基尼", u"马萨'拉蒂", u"法布雷加斯"] * 2
        for i in range(len(cars)):        
            cur.execute("INSERT INTO car VALUES(?,?)", (i, cars[i]))
        cur.execute("SELECT * FROM car")
        data = cur.fetchall()
        msg = ""
        for each in data:
             msg = msg + "id={0}, name={1} \n"\
                 .format(each[0], each[1].encode('utf-8'))
        if ui_demo:
            showinfo(u"汽车",msg)
        else:
            print msg
        
    except db.Error as e:
        print e
    finally:
        if con:
            con.close()


def print_sys_path():
    # sys may already import by Tkinter
    print sys.path


def demo_db_main():
    if MODE:
        print_sys_path()
        root = Tk()
        root.title("sqlite demo")
        root.geometry("200x50")
        Button(root, text="汽车", command=lambda:get_cars(MODE)).pack()
        root.mainloop()
    else:
        get_cars(MODE)


def group_split(lst,groups_to_split=3):
    """
    # 神一般存在的方法
    def group_it():
        from itertools import izip_longest
        group = lambda seq, n: [list(filter(bool, s)) for s in izip_longest(*[iter(seq)]*n)]
        return group
        
    usage:
        group_it(lst,numOfGroup)
    """
    
    
    # 以下是比较垃圾的传统方法
    if groups_to_split <= 0:
        print "ONLY positive group is allowed"
        return
    print "Original list" ,lst
    lstToReturn = []
    tmp = []
    lengthOfOriginalList = len(lst)
    for i in xrange(lengthOfOriginalList):
        tmp.append(lst[i])
        # list长度小于要分的组数，直接append即可
        if lengthOfOriginalList <= groups_to_split:
            lstToReturn.append(lst)
            break;
        # list的长度刚好够整分为group组， length % groups == 0
        elif lengthOfOriginalList % groups_to_split == 0:
            if (i+1) % groups_to_split == 0:
                lstToReturn.append(tmp)
                tmp = []
        # 剩下的就是list的长度不够整分了，整分之后还有剩余的元素
        else:
            # 先附加能整分的
            if (i+1) % groups_to_split == 0:
                lstToReturn.append(tmp)
                tmp = []
            # 再附加剩余的元素
            if i == lengthOfOriginalList // groups_to_split * groups_to_split:
                lstToReturn.append(lst[i:])
    return lstToReturn



class Robot:
    population = 0

    def __init__(self, name):
        import logging
        self.name = name
        Robot.population += 1
        logging.info("a new robot was born [{0}]"\
            .format(Robot.population))

    def show_name(self):
        print "my name is {0}, total robots number [{1}]"\
            .format(self.name, Robot.population)



    
if __name__ == '__main__':
    # print group_split([chr(i) for i in xrange(ord('A'),ord('z') + 1)], 5)
    # demo_db_main()
    # sendmail()
    import thread

    def hey():
        import time
        while 1:
            time.sleep(1)
            time.ctime()
            return 'yes' + str(time.localtime())
    thread.start_new_thread(hey, ())

    root = Tk()
    lbl = Label(root, text=hey)
    lbl.pack()
    root.mainloop()